<template>
  <div class="box" style="width: 100%;position: relative;">
    <div v-if="textVal" style="width: 100%;height: 100%;position: absolute;top: 0;left: 0;z-index: 20;">
      <el-input disabled v-model="textVal" placeholder="">
        <el-button @click="clearValue" slot="append" icon="el-icon-edit"></el-button>
      </el-input>
    </div>
    <el-cascader :change-on-select="changeOnSelect" :placeholder="placeholder" clearable ref="cascader"
      v-model="cascaderVal" style="width: 100%;height: 100%" v-else :props="props" @change="handleChange"></el-cascader>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cascaderVal: [],//级联选择器选中的数据
      textVal: '',
    }
  },
  props: {
    props: { //动态加载对象，直接传即可
      type: Object,
      default: () => {
        return {}
      }
    },
    defaultVal: { //默认显示文字,
      type: String,
      default: () => {
        return ''
      }
    },
    placeholder: {
      type: String,
      default: () => {
        return '请选择'
      }
    },
    changeOnSelect: { 
      type: Boolean,
      default: () => {
        return false
      }
    },
  },

  mounted() {
    this.textVal = this.defaultVal
  },
  methods: {
    clearValue() {
      this.textVal = ''

      this.$nextTick(() => { //清空选中项
        this.handleChange()
      })
    },
    handleChange() {
      if (this.changeOnSelect) {
        this.$nextTick(() => {

          const dom = document.getElementsByClassName("el-radio is-checked");
          //这里我把dom打出来看了 最后一个选项才是我选中的节点 即[length-1] 有的博主写的是 第一个元素 即[0] 大家自行尝试
          let radioDom = dom[dom.length - 1];
          const brother = radioDom.nextElementSibling;
          brother.click();
        });
      }

      let obj = {
        ids: [],
        names: []
      }
      if (this.$refs.cascader.getCheckedNodes().length > 0) {
        let data = this.$refs.cascader.getCheckedNodes()[0].pathLabels;
        obj.ids = this.cascaderVal
        obj.names = data
      } else {
      }
      console.log(obj, this.defaultVal, '选择的值')
      this.$emit('getData', obj)
    }
  }
}
</script>

<style lang="less" scoped>
.box {
  /deep/ .el-input__suffix {
    display: flex;
    align-items: center;
  }
}
</style>